<template>
  <div class="row">
    <div class="col-sm-12">
      <div class="card-box">
        <div class="progress progress-lg">
          <div
            class="progress-bar progress-bar-warning progress-bar-striped active"
            role="progressbar"
            :aria-valuenow="upload_rate_num"
            aria-valuemin="0"
            aria-valuemax="100"
            :style="{width: upload_rate}"
          >
            <span>{{ upload_rate }} Complete</span>
          </div>
        </div>

        <!-- /.progress .no-rounded -->
        <input
          @change="get_file_md5"
          ref="file"
          type="file"
          class="dropify"
          data-height="150"
          data-max-file-size="1024M"
        >
      </div>
    </div>
    <!-- end col -->
    <div
      v-show="upload_success_show"
      class="sweet-alert showSweetAlert visible"
      tabindex="-1"
      data-has-cancel-button="false"
      data-has-confirm-button="true"
      data-allow-ouside-click="false"
      data-has-done-function="false"
      data-timer="null"
      style="display: block; margin-top: -164px;"
    >
      <div class="icon error" style="display: none;">
        <span class="x-mark">
          <span class="line left"></span>
          <span class="line right"></span>
        </span>
      </div>
      <div class="icon warning" style="display: none;">
        <span class="body"></span>
        <span class="dot"></span>
      </div>
      <div class="icon info" style="display: none;"></div>
      <div class="icon success" style="display: none;">
        <span class="line tip"></span>
        <span class="line long"></span>
        <div class="placeholder"></div>
        <div class="fix"></div>
      </div>
      <div
        class="icon custom"
        style="display: block; background-image: url(&quot;/static/assets/plugins/bootstrap-sweetalert/thumbs-up.jpg&quot;);width:80px; height:80px"
      ></div>
      <h2>牛逼啊!</h2>
      <p class="lead text-muted" style="display: block;">Upload Success.</p>
      <p>
        <button
          class="confirm btn btn-lg btn-primary"
          tabindex="1"
          style="display: inline-block;"
          @click="upload_success"
        >OK</button>
      </p>
    </div>
  </div>
  <!-- end col -->
</template>

<script>
import SparkMD5 from "spark-md5";
import axios from "axios";
export default {
  data() {
    return {
      code: -1,
      md5: "", // 存储文件MD5值的变量
      upload_success_show: 0,
      upload_rate_num: 0,
      upload_rate: "0%" // 上传比例
    };
  },
  methods: {
    upload_success() {
      (this.upload_success_show = 0), (this.upload_rate = "0%"); // 初始化进度条
      this.$emit('refersh_all_component', '上传组件上传成功')
    },
    get_file_md5() {
      this.file = this.$refs.file.files[0];
      var fileReader = new FileReader();
      var dataFile = this.file;
      var spark = new SparkMD5(); //创建md5对象（基于SparkMD5）
      if (dataFile.size > 1024 * 1024 * 10) {
        var data1 = dataFile.slice(0, 1024 * 1024 * 10); //将文件进行分块 file.slice(start,length)
        fileReader.readAsBinaryString(data1); //将文件读取为二进制码
      } else {
        fileReader.readAsBinaryString(dataFile);
      }
      fileReader.onload = e => {
        spark.appendBinary(e.target.result);
        var md5 = spark.end();
        this.md5 = md5;
      };
    },
    
  },
  watch: {
    md5(newval, oldval) {
      if (this.md5 == "") {
        return;
      }
      this.upload_rate = "0%"; // 初始化进度条
      let form_data = new FormData();
      form_data.append("filename", this.file.name); // 待上传文件
      form_data.append("file_md5", newval); // 待上传文件
      axios({
        url: this.$api + "/api/file/upload_md5/",
        method: "post",
        data: form_data,
        withCredentials: true, // 携带set_cookie
      }).then(res => {
        console.log(res.data);
        this.code = res.data.code; // {0 : 秒传成功 4004 : 不存在}
        if (this.code == 0) {
          console.log("秒传成功");
          console.log(res.data);
          console.log("-------------------");
          this.upload_success_show = 1;
          this.upload_rate_num = 100;
          this.upload_rate = "100.00%"; // 上传结束
        }
        if (this.code == 40003) {
          console.log("秒传失败");
          console.log(res.data);
          console.log("-------------------");
        }
        if (this.code == 40004) {
          console.log("md5值不存在，需要上传文件");
          console.log(res.data);
          console.log("-------------------");
          form_data.append("file", this.file); // 待上传文件
          console.log(form_data);
          axios({
            url: this.$api + "/api/file/upload/",
            method: "post",
            headers: { "Content-Type": "multipart/form-data" },
            data: form_data,
            withCredentials: true, // 携带set_cookie
            onUploadProgress: e => {
              if (e.lengthComputable) {
                var rate = e.loaded / e.total;
                if (rate < 1) {
                  this.upload_rate = (rate * 100).toFixed(2) + "%";
                  this.upload_rate_num = (rate * 100).toFixed(2);
                }
              }
            }
          }).then(res => {
            if (res.data.code == 0) {
              this.upload_success_show = 1;
              this.upload_rate_num = 100;
              this.upload_rate = "100.00%"; // 上传结束
            }
          });
        }
      });
      this.md5 = "";
      // window.location.reload()
    }
  }
};
</script>